package cyapps.config;

import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author CyApps
 */
public class ConfigFile {
	private Path                             path;
	private Map<String, Map<String, String>> configs;
	
	public ConfigFile(Path path) throws IOException {
		this.path = path;
		this.configs = new HashMap<>(this.load());
		if (configs == null)
		    throw new IOException("File konnte nicht gelesen werden");
	}
	/**
     * 
     */
	public ConfigFile() {
		this.path = Paths.get("");
		this.configs = new HashMap<>();
	}
	public Map<String, Map<String, String>> load() throws IOException {
		String name = "Undefined";
		Map<String, Map<String, String>> configs = new HashMap<>();
		Map<String, String> map = new HashMap<>();
		List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
		for (String line : lines) {
			line = line.trim();
			if ((line.length() == 0) || (line == "") || (line.charAt(0) == ';')
			        || (line.charAt(0) == '#')) {
				continue;
			}
			if (!(line.charAt(0) == '[')) {
				int s = line.indexOf('=');
				if (s == -1) {
					continue;
				}
				map.put(line.substring(0, s).trim(), line.substring(s + 1, line.length()).trim());
			} else {
				if (!map.isEmpty()) {
					configs.put(new String(name), new HashMap<>(map));
				}
				map.clear();
				name = line.substring(1, line.length() - 1);
				continue;
			}
		}
		if (!map.isEmpty()) {
			configs.put(name, new HashMap<>(map));
		}
		return configs;
	}
	public void write(Path path) throws IOException {
		Writer bw = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
		bw.write("");
		for (String string : configs.keySet()) {
			bw.append(String.format("[%s]%n", string));
			Map<String, String> properties = configs.get(string);
			for (String key : properties.keySet()) {
				bw.append(key + "=" + properties.get(key) + "\r\n");
			}
		}
		bw.close();
	}
	public Map<String, Map<String, String>> getConfigs() {
		return configs;
	}
	public String getValue(String section, String key) {
		return configs.get(section).get(key);
	}
	public Path getPath() {
		return path;
	}
	public String getFileName() {
		return Paths.get(path.toUri()).getFileName().toString();
	}
	/**
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return configs.toString();
	}
}
